package com.coolmusic;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;

import java.io.File;
import java.lang.ref.WeakReference;

public class SettingsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        // 设置 Toolbar（兼容旧版）
        androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("设置");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        // 加载偏好设置碎片
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.preference_container, new SettingsFragment())
                .commit();
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public static class SettingsFragment extends PreferenceFragmentCompat {
        private static final int REQUEST_STORAGE_PERMISSION = 1;
        private CacheTask cacheTask;

        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.settings_preferences, rootKey);

            // 主题切换（兼容 Android 5.0 主题模式）
            ListPreference themePreference = findPreference("theme_mode");
            if (themePreference != null) {
                themePreference.setOnPreferenceChangeListener((preference, newValue) -> {
                    applyTheme((String) newValue);
                    return true;
                });
            }

            // 清理缓存（简化权限逻辑，适配 API 21）
            Preference clearCachePreference = findPreference("clear_cache");
            if (clearCachePreference != null) {
                clearCachePreference.setOnPreferenceClickListener(preference -> {
                    // 移除 Android 6.0+ 动态权限检查（API 21 无需动态申请）
                    startCacheTask();
                    return true;
                });
            }
        }

        private void applyTheme(String themeValue) {
            switch (themeValue) {
                case "light":
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                    break;
                case "dark":
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                    // 移除 "system" 模式（Android 5.0 不支持跟随系统主题）
            }
            Activity activity = requireActivity();
            if (!activity.isFinishing() && !activity.isDestroyed()) {
                activity.recreate();
            }
        }

        // 移除动态权限请求（API 21 直接获取权限）
        private void startCacheTask() {
            if (cacheTask == null || cacheTask.getStatus() == AsyncTask.Status.FINISHED) {
                cacheTask = new CacheTask(this);
                cacheTask.execute();
            }
        }

        // 缓存清理任务（适配旧版文件路径）
        private static class CacheTask extends AsyncTask<Void, Void, Long> {
            private final WeakReference<SettingsFragment> fragmentRef;

            public CacheTask(SettingsFragment fragment) {
                fragmentRef = new WeakReference<>(fragment);
            }

            @Override
            protected Long doInBackground(Void... voids) {
                SettingsFragment fragment = fragmentRef.get();
                if (fragment == null) return 0L;

                long cacheSize = 0;
                // 仅清理内部缓存（外部缓存路径在 API 21 可能不同）
                cacheSize += getDirectorySize(fragment.requireContext().getCacheDir());
                return cacheSize;
            }

            @Override
            protected void onPostExecute(Long size) {
                SettingsFragment fragment = fragmentRef.get();
                if (fragment == null) return;
                fragment.clearAppCache(size);
            }

            private static long getDirectorySize(File directory) {
                if (directory == null || !directory.exists() || !directory.isDirectory()) return 0;
                long totalSize = 0;
                File[] files = directory.listFiles();
                if (files != null) {
                    for (File file : files) {
                        if (file.isFile()) totalSize += file.length();
                        else totalSize += getDirectorySize(file);
                    }
                }
                return totalSize;
            }
        }

        private void clearAppCache(long cacheSize) {
            deleteDirectory(requireContext().getCacheDir());
            Toast.makeText(requireContext(), "已清理 " + formatSize(cacheSize) + " 缓存", Toast.LENGTH_SHORT).show();
        }

        private boolean deleteDirectory(File directory) {
            if (directory == null || !directory.exists()) return true;
            if (directory.isDirectory()) {
                File[] files = directory.listFiles();
                if (files != null) {
                    for (File file : files) {
                        deleteDirectory(file);
                    }
                }
            }
            return directory.delete();
        }

        private String formatSize(long size) {
            if (size < 1024) return size + " B";
            int unit = (int) (Math.log(size) / Math.log(1024));
            return String.format("%.1f %s", size / Math.pow(1024, unit),
                    new String[]{"KB", "MB", "GB", "TB"}[unit]);
        }
    }
}